package com.glSto.service;

import com.glSto.rep.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest // 启动 Spring 上下文
@Service
public class MdmServiceBatchTest {

    // 批处理大小
    private static final int BATCH_SIZE = 100;

    @Autowired
    private RestTemplate restTemplate;
    public void runBatchProcessingTest() {
        System.out.println("开始测试批处理功能...");

        // 创建假数据
        List<ResponseData.Collection.Items> mockItems = createMockItems(1000);
        System.out.println("已创建 " + mockItems.size() + " 条测试数据");

        // 执行批处理
        processItemsInBatches(mockItems, restTemplate);

        System.out.println("批处理测试完成");
    }

    /**
     * 批量处理数据（同步方式，避免并发问题）
     */
    private void processItemsInBatches(List<ResponseData.Collection.Items> items, RestTemplate restTemplate) {
        int totalItems = items.size();
        System.out.println("开始批量处理 " + totalItems + " 条数据，每批 " + BATCH_SIZE + " 条");

        // 分批处理
        for (int i = 0; i < totalItems; i += BATCH_SIZE) {
            int endIndex = Math.min(i + BATCH_SIZE, totalItems);
            List<ResponseData.Collection.Items> batch = items.subList(i, endIndex);

            System.out.println("开始处理第 " + (i + 1) + "-" + endIndex + " 条数据");

            // 处理当前批次
            processBatch(batch, restTemplate, i + 1);

            System.out.println("第 " + (i + 1) + "-" + endIndex + " 条数据处理完成");

            // 批次间休眠，避免对目标系统压力过大
            if (endIndex < totalItems) {
                try {
                    Thread.sleep(100); // 缩短休眠时间用于测试
                    System.out.println("批次间休眠0.1秒...");
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }

        System.out.println("所有 " + totalItems + " 条数据处理完成");
    }

    /**
     * 处理单个批次的数据
     */
    private void processBatch(List<ResponseData.Collection.Items> batch, RestTemplate restTemplate, int startIndex) {
        int successCount = 0;
        int failureCount = 0;

        for (int i = 0; i < batch.size(); i++) {
            ResponseData.Collection.Items item = batch.get(i);
            try {
                if (processSingleItem(item, restTemplate)) {
                    successCount++;
                } else {
                    failureCount++;
                }
            } catch (Exception e) {
                failureCount++;
                System.out.println("处理第 " + (startIndex + i) + " 条数据时发生异常: " + e.getMessage());
            }

            // 每处理10条数据打印一次进度
            if ((i + 1) % 10 == 0 || i == batch.size() - 1) {
                System.out.println("批次进度: " + (i + 1) + "/" + batch.size() + "，成功: " + successCount + "，失败: " + failureCount);
            }
        }

        System.out.println("批次处理完成，成功: " + successCount + "，失败: " + failureCount);
    }

    private static final String TARGET_API_URL = "https://sto.njphzh.com:13500/v1/openapi/sto/mdm/material";

    /**
     * 处理单条数据记录
     */
    private boolean processSingleItem(ResponseData.Collection.Items item, RestTemplate restTemplate) {
        try {
            List<ResponseData.Collection.Items.Data> dataList = item.getData();
            Map<String, String> fieldMap = new HashMap<>();

            // 构建字段映射
            for (ResponseData.Collection.Items.Data data : dataList) {
                fieldMap.put(data.getName(), data.getValue());
            }

            String matnr = fieldMap.get("MATNR");
            System.out.println("开始处理物料: " + matnr);

            Map<String, Object> request = new HashMap<>();
            request.put("dataType", "STO_MDM_01");
            request.put("appKey", "stoApply");
            request.put("timestamp", System.currentTimeMillis());
            request.put("accessToken", "5411706e6b4a662481bcbeed9f4aec60");
            request.put("operationType", "CREATE");

            Map<String, Object> dataObj = new HashMap<>();
            dataObj.put("materialCode", fieldMap.get("MATNR"));
            dataObj.put("materialName", fieldMap.get("MAKTX"));
            dataObj.put("uom", fieldMap.get("MEINS"));
            dataObj.put("price", fieldMap.get("VERPR"));
            dataObj.put("materialGroup", fieldMap.get("MATKL"));
            dataObj.put("shopGroup", fieldMap.get("EKGRP"));
            dataObj.put("sourceMaterialId", fieldMap.get("MATNR"));
            dataObj.put("orderNum", 1);
            dataObj.put("remark", null);
            dataObj.put("sourceApiData", fieldMap);
            request.put("data", dataObj);

            HttpHeaders targetHeaders = new HttpHeaders();
            targetHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> targetEntity = new HttpEntity<>(request, targetHeaders);
            ResponseEntity<String> response = restTemplate.exchange(TARGET_API_URL, HttpMethod.POST, targetEntity, String.class);
            if (response != null) {
                System.out.println("创建成功");
                return true;
            } else {
                System.out.println("创建失败");
                return false;
            }
        } catch (Exception e) {
            System.out.println("处理数据时发生异常: " + e.getMessage());
            return false;
        }
    }

    /**
     * 创建模拟数据项
     * @param count 数据项数量
     * @return 模拟的数据项列表
     */
    private List<ResponseData.Collection.Items> createMockItems(int count) {
        List<ResponseData.Collection.Items> items = new ArrayList<>();

        for (int i = 1; i <= count; i++) {
            ResponseData.Collection.Items item = new ResponseData.Collection.Items();
            List<ResponseData.Collection.Items.Data> dataList = new ArrayList<>();

            // 添加必要的字段数据
            dataList.add(createDataField("MATNR", "MATNR" + String.format("%06d", i)));
            dataList.add(createDataField("MAKTX", "物料名称" + i));
            dataList.add(createDataField("MEINS", "件"));
            dataList.add(createDataField("VERPR", String.valueOf(100.0 + (i % 100))));
            dataList.add(createDataField("MATKL", "MATKL" + (i % 10)));
            dataList.add(createDataField("EKGRP", "EKGRP" + (i % 5)));

            item.setData(dataList);
            items.add(item);
        }

        return items;
    }

    /**
     * 创建单个数据字段
     * @param name 字段名
     * @param value 字段值
     * @return 数据字段对象
     */
    private ResponseData.Collection.Items.Data createDataField(String name, String value) {
        ResponseData.Collection.Items.Data data = new ResponseData.Collection.Items.Data();
        data.setName(name);
        data.setValue(value);
        return data;
    }
}
